import {
  useState,
  useMemo,
  useCallback,
  forwardRef,
  useImperativeHandle,
  Ref,
} from 'react';
import { Table, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import RegExpInput from './RegExpInput';
import { useUpdateEffect } from 'ahooks';
export type IOutTableValue = {
  primaryKey?: string;
  list: {
    name: string;
    path?: string;
  }[];
};
export type IOutTable = {
  getValue: () => Promise<IOutTableValue>;
};
const uniqueReg = /^[\w]+$/;
const pathReg = /^[\w\.\$]+$/;
function OutTable(
  {
    value,
    keys,
    isPrimaryKey,
  }: { value?: IOutTableValue; keys: string[]; isPrimaryKey?: boolean },
  ref: Ref<IOutTable>,
) {
  const [primaryKey, $primaryKey] = useState(value?.primaryKey);
  const [dataSource, $dataSource] = useState<
    (IOutTableValue['list'][number] & { status?: 'error' })[]
  >(() => {
    if (value?.list?.length) {
      return value.list;
    } else {
      return keys.map((item) => ({
        name: item,
      })) as unknown as IOutTableValue['list'];
    }
  });
  useUpdateEffect(() => {
    $dataSource(value?.list || []);
    $primaryKey(value?.primaryKey);
  }, [value]);

  useImperativeHandle(
    ref,
    () => ({
      getValue: async () => {
        if (isPrimaryKey && !primaryKey) {
          message.error('唯一标识不能为空');
          return Promise.reject('唯一标识不能为空');
        }
        const index = dataSource.findIndex((item) => !item.path);
        if (index != -1) {
          $dataSource((list) => {
            const newList = [...list];
            newList[index] = {
              ...newList[index],
              status: 'error',
            };
            return newList;
          });
          message.error('参数路径不能为空');
          return Promise.reject('参数路径不能为空');
        }
        return {
          primaryKey,
          list: dataSource,
        };
      },
    }),
    [primaryKey, dataSource, isPrimaryKey],
  );

  const handleChange = useCallback((name, value) => {
    $dataSource((data) => {
      const newData = [...data];
      const index = newData.findIndex((item) => item.name === name);
      newData[index] = {
        ...newData[index],
        path: value,
        status: !!value ? undefined : 'error',
      };
      return newData;
    });
  }, []);
  const columns: ColumnsType<(typeof dataSource)[number]> = useMemo(
    () => [
      {
        title: '参数',
        width: '50%',
        dataIndex: 'name',
        key: 'name',
        className: 'name',
      },
      {
        title: '路径',
        width: '50%',
        dataIndex: 'path',
        key: 'path',
        render: (value, recerd) => {
          return (
            <RegExpInput
              placeholder="如: $.Rows"
              value={value}
              reg={pathReg}
              status={recerd.status}
              onChange={(event) =>
                handleChange(recerd.name, event.target.value)
              }
            />
          );
        },
      },
    ],
    [],
  );

  return (
    <div className="outTable">
      {isPrimaryKey && (
        <div className="uniqueBox">
          <span>
            <span className="required">*</span>唯一标识
          </span>
          <RegExpInput
            value={primaryKey}
            reg={uniqueReg}
            onChange={(e) => $primaryKey(e.target.value)}
            maxLength={50}
            placeholder="如: id"
            status={primaryKey === '' ? 'error' : undefined}
          />
        </div>
      )}
      <Table
        pagination={false}
        size="small"
        bordered
        columns={columns}
        dataSource={dataSource}
        rowKey="name"
      />
    </div>
  );
}

export default forwardRef(OutTable);
